package org.nobject.common.swing.g;

import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Insets;

public class GFlowLayout extends GLayout {

	/* (non-Javadoc)
	 * @see java.awt.LayoutManager#addLayoutComponent(java.lang.String, java.awt.Component)
	 */
	public void addLayoutComponent(String name, Component comp) {
		
	}
	
	int hgap=5;
	int vgap=5;
	/* (non-Javadoc)
	 * @see java.awt.LayoutManager#layoutContainer(java.awt.Container)
	 */
	public void layoutContainer(Container target) {
		Insets insets = target.getInsets();
		//最大宽度=目标宽度-(内左边距+内右边距+内部的padding*2)
		int maxwidth = target.getWidth() - (insets.left + insets.right + hgap*2);
		int childcount = target.getComponentCount();
		int x = 0;
		int y = insets.top + vgap;
		int rowh = 0, start = 0;

		for (int i = 0 ; i < childcount ; i++) {
		    Component cp = target.getComponent(i);
		    if (cp.isVisible()) {
				Dimension d = cp.getPreferredSize();
				cp.setSize(d.width, d.height);
				
				//如果x起点+宽度小于最大宽度
				if ((x == 0) || ((x + d.width) <= maxwidth)) {
				    if (x > 0) x += hgap;
				    x += d.width;
				    rowh = Math.max(rowh, d.height);
				} else {
				    moveComponents(target, insets.left + hgap, y, maxwidth - x, rowh, start, i);
				    x = d.width;
				    y += vgap + rowh;
				    rowh = d.height;
				    start = i;
				}
		    }
		}
		moveComponents(target, insets.left + hgap, y, maxwidth - x, rowh, start, childcount);
	}

	/**
	 * @param target
	 * @param x
	 * @param y
	 * @param width
	 * @param height
	 * @param rowStart
	 * @param rowEnd
	 * @param ltr
	 */
	private void moveComponents(Container target, int x, int y, int width, int height,int rowStart, int rowEnd) {
		x +=0;
		for (int i = rowStart ; i < rowEnd ; i++) {
			Component m = target.getComponent(i);
			if (m.isVisible()) {
				m.setLocation(x, y + (height - m.getHeight()) / 2);
				x += m.getWidth() + hgap;
			}
		}
	}
	
	/* (non-Javadoc)
	 * @see java.awt.LayoutManager#minimumLayoutSize(java.awt.Container)
	 */
	public Dimension minimumLayoutSize(Container parent) {
		return new Dimension(100,100);
	}

	/* (non-Javadoc)
	 * @see java.awt.LayoutManager#preferredLayoutSize(java.awt.Container)
	 */
	public Dimension preferredLayoutSize(Container parent) {
		return new Dimension(100,100);
	}

	/* (non-Javadoc)
	 * @see java.awt.LayoutManager#removeLayoutComponent(java.awt.Component)
	 */
	public void removeLayoutComponent(Component comp) {
		
	}
}
